package celiasoft.itasalib.query.resultparser;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.htmlcleaner.TagNode;
import org.w3c.dom.Document;

import android.util.Log;
import celiasoft.itasalib.query.ResultsMetaInfo;
import celiasoft.itasalib.structures.CalendarDay;
import celiasoft.itasalib.structures.DataElement;

public class QueryCalendarResultParser extends IQueryResultParser {

	private static final String TAG = "itasalib.parser.QueryCalendarResultParser";
	private final SimpleDateFormat _sdf = new SimpleDateFormat("yyyyMMdd");

	
	public List<DataElement> parse(Document doc, ResultsMetaInfo meta) {
		return null;
	}

		
	@Override
	public List<DataElement> parse(TagNode root, ResultsMetaInfo meta) {
		
		ArrayList<DataElement> res = new ArrayList<DataElement>();

		List<TagNode> days = HTMLParsingHandler.getElementListByClass(root, "td", new String[]{"monthreg", "monthon"});
		
		if(days.size() < 1 ){
			return res;
		}
				
		for(TagNode n: days){
			DataElement el = parseDayNode(n);
			if(el != null){
				res.add(el);
			}
		}
		
		if(res.size() > 0){
			setMetaData(null, meta);
		}
		
		return res;
	}
	
	private DataElement parseDayNode(TagNode n) {
		
		CalendarDay cDay = null;
		
		List<TagNode> links = HTMLParsingHandler.getLinksListByClass(n, "psf");
		
		if(!links.isEmpty()){
			TagNode node = links.get(0);
			String dateStr = node.getAttributeByName("href").toString();
			Date day = null;
			
			if(dateStr != null){
				String dayStr = dateStr.replace("day.php?cal=itasa&amp;getdate=", "");
				
				try {
					day = (Date) _sdf.parse(dayStr);
				}catch (ParseException e1) {
					e1.printStackTrace();
					Log.e(TAG, "Unable to parse date value.");
				}
			}
			
			if(day != null){
				cDay = new CalendarDay(day);
				cDay.setShows(getDayShows(n));
				
			}
		}
		
		return cDay;
	}

	private List<String> getDayShows(TagNode n) {
		
		List<String> shows = new ArrayList<String>();
		
		List<TagNode> links = HTMLParsingHandler.getLinksListByClass(n, "ps3");
		
		for(TagNode node : links){
			String txt = node.getText().toString();
			if(txt != null && txt.trim().compareToIgnoreCase("") != 0){
				shows.add(txt);
			}
		}
		
		return shows;
	}
}


































